#!/usr/bin/env python3
import argparse
import logging
from operator import index
import os
import sys
import threading

import urllib3

from pyzabbix import ZabbixAPI


urllib3.disable_warnings()

def get_zabbix_connection(zbx_url, zbx_user, zbx_password):
    """
    Sometimes pyzabbix and py-zabbix library can replace each other.
    This is a wrapper, we don't care about what pip-module we install.
    Return ZabbixAPI object
    """
    # pyzabbix library, with user\password in login method. It's GOOD library
    logging.debug("Try connect to Zabbix by pyzabbix...")
    try:
        zbx_pyzabbix = ZabbixAPI(zbx_url)
        zbx_pyzabbix.session.verify = False
        zbx_pyzabbix.login(zbx_user, zbx_password)
        return zbx_pyzabbix
    except Exception as e:
        logging.exception(e)

    # py-zabbix library, with user\password in ZabbixAPI
    logging.debug("Try connect to Zabbix by py-zabbix...")
    try:
        zbx_py_zabbix = ZabbixAPI(zbx_url, user=zbx_user, password=zbx_password)
        zbx_py_zabbix.session.verify = False
        return zbx_py_zabbix
    except Exception as e:
        logging.exception(e)
    # choose good API

    raise Exception("Some error in pyzabbix or py_zabbix module, see logs")

def environ_or_required(key):
    "Argparse environment vars helper"
    if os.environ.get(key):
        return {"default": os.environ.get(key)}
    else:
        return {"required": True}

def parse_args():
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--zabbix-url",
        action="store",
        help="REQUIRED. May be in ZABBIX_URL env var",
        **environ_or_required("ZABBIX_URL")
    )
    parser.add_argument(
        "--zabbix-username",
        action="store",
        help="REQUIRED. May be in ZABBIX_USERNAME env var",
        **environ_or_required("ZABBIX_USERNAME")
    )
    parser.add_argument(
        "--zabbix-password",
        action="store",
        help="REQUIRED. May be in ZABBIX_PASSWORD env var",
        **environ_or_required("ZABBIX_PASSWORD")
    )


    parser.add_argument("--debug", action="store_true", help="Show debug output")


    args = parser.parse_args()
    return args

def init_logging(level):
    logger_format_string = "%(asctime)s %(levelname)-8s %(message)s"
    logging.basicConfig(level=level, format=logger_format_string, stream=sys.stdout)

def delete_thread(zabbix_,items):
    for item in items:
        # items.remove(item)
        zabbix_.host.delete(item.get("hostid"))

def update_hosts(zabbix_,items):
    for item in items:
        zabbix_.host.update(hostid=item.get("hostid"),status=1)

def get_item_cache(zabbix):
    "Return dict 'hostname, key_'=>itemid"
    result = zabbix.item.get(
        output=["key_", "itemid"], selectHosts=["name"], webitems=True
    )
    item2itemid = {}  # key: "hostname,itemname", value: itemid
    for i in result:
        if i["hosts"]:
            item2itemid["{},{}".format(i["hosts"][0]["name"], i["key_"])] = i["itemid"]
    return item2itemid

if __name__ == "__main__":
    args = parse_args()
    level = logging.INFO
    if args.debug:
        level = logging.DEBUG
    init_logging(level=level)

    zabbix_ = get_zabbix_connection(
        args.zabbix_url, args.zabbix_username, args.zabbix_password
    )

    # logging.info("All files will be save in {}".format(os.path.abspath(args.directory)))
    items = zabbix_.host.get()
    print(len(items))
    threads = []
    for i in range(8):
        index = int(len(items)/8)
        items_i = items[i*index:(i+1)*index]
        if i == 7:
            items_i = items[i*index:]
        thread = threading.Thread(target=delete_thread, args=(zabbix_,items_i))
        thread.start()
        threads.append(thread)
    for t in threads:
        t.join()
    # print(account,len(items))
    # items = zabbix_.item.get({
    #     "search": {
    #         "key_": "custom.time"
    #     },
    # })
    # for item in items:
    #     print(item["key_"])
    # iface = zabbix_.item.get(
    #     output="extend", search={"key_": "vfs.file.cksum[{$HAPROXY_CONFIG}]"}
    # )
    # items = zabbix_.drule.create({
    #     "delay": "180",
    #     "iprange": "192.168.1.1-255",
    #     "name": "custom.disk.discovery",
    #     "dchecks": [
    #         {
    #             "type": "9",
    #             "key_": "system.uname",
    #             "ports": "10050",
    #             "uniq": "0"
    #         }
    #     ],
    # })
    # print(zabbix_.auth)
    # for item in items:
    #     if item["host"] == "act12.leiting.com":
    #         txt = zabbix_.configuration.export(
    #             format="json", options={"hosts": [item["hostid"]]}
    #         )
    #         print(txt)
